<?php

namespace app\api\controller\v2;


use app\api\lib\exception\MissException;
use app\api\lib\exception\SuccessMessage;
use app\api\model\Order;
use app\api\service\OrderService;
use app\api\service\TokenService;
use app\api\validate\IdMustInt;
use think\Db;
use app\api\model\Goods as GoodsModel;
use think\Exception;

class OrderController extends BaseController
{
    public function _initialize()
    {
        $this->uid = TokenService::getCurrentUid();
        $this->points = Db::table('payset')->find()['ratio_points'];
    }

    //订单列表
    public function getOrderList($status)
    {
        Order::autoConfirmOrder($this->uid);
        $common_time = config('setting.auto_abate_time') * 60 * 60;
        $collage_time = config('setting.auto_collage_abate_time') * 60 * 60;
        Order::abateOrder(['status'=>1,'collage'=>1,'user_id'=>$this->uid],$common_time);
        Order::abateOrder(['status'=>1,'collage'=>0,'user_id'=>$this->uid],$collage_time);
        if($status == 0){
            $result = Db::table('order')->where('user_id',$this->uid)->order('create_time','desc')->field(['id','sn','type','is_comment','status','true_price'])->select();
        }
        if($status == 1){
            $result = Db::table('order')->where('status',1)->where('user_id',$this->uid)->order('create_time','desc')->field(['id','sn','type','is_comment','status','true_price'])->select();
        }
        if($status == 2){
            $result = Db::table('order')->where('status','in',2)->where('user_id',$this->uid)->order('create_time','desc')->field(['id','sn','type','is_comment','status','true_price'])->select();
        }
        if($status == 3){
            $result = Db::table('order')->where('status','eq',3)->where('user_id',$this->uid)->order('create_time','desc')->field(['id','sn','type','is_comment','status','true_price'])->select();
        }
        if($status == 4){
            $result = Db::table('order')->where('is_comment','1')->where('status','eq',4)->where('user_id',$this->uid)->order('create_time','desc')->field(['id','sn','type','is_comment','status','true_price'])->select();
        }
        foreach ($result as $key => $value){
            $result[$key]['goods'] = [];
            $result[$key]['count'] = 0;
            foreach (Db::table('order_detail')->where('order_id',$value['id'])->select() as $k => $v){
                $result[$key]['goods'][$k] = GoodsModel::where('id',$v['food_id'])->field(['goods_name','cover_img','cover_img_origin','sale_price'])->find();
                $result[$key]['goods'][$k]['count'] = $v['count'];
                $result[$key]['count'] += $v['count'];
            }
            $result[$key]['points'] = Db::table('points_bill')->where(['relation_id' => $value['id'],'status' => 0,'state' => 1])->field('points')->find()['points']/ $this->points;
        }
        throw new SuccessMessage([
          'data' =>  $result
        ]);
    }

    //订单详情
    public function getOrderInfo($id)
    {
        (new IdMustInt())->goCheck();
        $result = Db::table('order')->where('user_id',$this->uid)->where('id',$id) ->field(['id','sn','update_time','note','table','create_time','is_comment','status','price','true_price','coupon_id','type','name','phone','address'])->find();
        if(!$result){
            throw new MissException();
        }
        $result['points'] = Db::table('points_bill')->where(['relation_id' => $result['id'],'status' => 0,'state' => 1])->field('points')->find()['points']/ $this->points;
        $coupon = Db::table('coupon_category')->where('id',$result['coupon_id'])->find();
        $result['coupon'] = 0;
        if($coupon['coupon_cate_cate'] == 1){
            $result['coupon'] = $coupon['amount_cash'];
        }
        if($coupon['coupon_cate_cate'] == 2){
            $result['coupon'] = $result['price'] * (1 - $coupon['discount_ticket']);
        }

        $result['goods'] = [];
        foreach (Db::table('order_detail')->where('order_id',$result['id'])->select() as $k => $v){
            $result['goods'][$k] = GoodsModel::where('id',$v['food_id'])->field(['goods_name','cover_img','cover_img_origin','sale_price'])->find();
            $result['goods'][$k]['count'] = $v['count'];
        }
        $result['points'] = Db::table('points_bill')->where(['relation_id' => $result['id'],'status' => 0,'state' => 1])->field('points')->find()['points']/ $this->points;
        $result['get_points'] = Db::table('points_bill')->where(['relation_id' => $result['id'],'status' => 1,'state' => 1])->field('points')->find()['points'];

        if($result['type'] == 1){
            throw new SuccessMessage([
//                'data' => hiddenArray($result,['id','table','sn','coupon_id','create_time','update_time','note']),
                'data' => $result,
            ]);
        }
//        $result['table'] = Db::table('table')->where(['id' => $result['table']])->field('name')->find()['name'];
        $result['user'] = Db::table('user')->where('id',$this->uid)->field(['nickname','tel'])->find();
        throw new SuccessMessage([
//            'data' => hiddenArray($result,['id','coupon_id']),
            'data' => $result,
        ]);
    }

    //用户确认收货
    public function confirmOrder()
    {
        $sn = $this->request->param('sn');
        $order = Order::field('id,status')->where(['sn'=>$sn])->find();
        if($order->getData('status') != 3){
            throw new MissException(['msg'=>'订单异常,请联系管理员']);
        }
        try{
            Order::where(['sn'=>$sn])->update(['status'=>4]);
        }catch(Exception $e){
            throw new MissException(['msg'=>'订单处理失败,请稍后再试!']);
        }
        throw new SuccessMessage(['msg'=>'处理订单处理成功!']);
    }

    //取消订单
    public function closeOrder()
    {
        (new IdMustInt())->goCheck();
        $id = input('id/d');
        $res = OrderService::checkOrderInUser($id);
        if($res['status'] != '待付款'){
            throw new MissException();
        }
        $res->save(['status' => 8]);
        throw new SuccessMessage();
    }




    public function refund()
    {
        $order_id = input('post.')['id'];
        (new IdMustInt())->goCheck();
        $res = OrderService::checkOrderInUser($order_id);
        if(!in_array($res['status'],['已付款'])){
            throw new MissException();
        }
        Order::where('id', $order_id)->update(['status' => 9,'refund_reason' => input('post.')['refund_reason']]);
        throw new SuccessMessage();
    }

}